<template>
    <div>
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>权限管理</el-breadcrumb-item>
        <el-breadcrumb-item>角色列表</el-breadcrumb-item>
      </el-breadcrumb>
      <!--卡片视图-->
      <el-card>
        <!--添加角色按钮-->
        <el-row>
          <el-col>
            <el-button type="primary">添加角色</el-button>
          </el-col>
        </el-row>
        <!--角色列表区域-->
        <el-table
          :data="rolesList"
          stripe
          border
          style="width: 100%">
          <!--展开列-->
          <el-table-column type="expand">
            <template slot-scope="scope">
              <el-row v-for="(item,i1) in scope.row.children" :key="item.id"
                :class="['bdbottom',i1 ===0 ? 'bdtop': '']" type="flex" align="middle">
                <!--渲染一级权限-->
                <el-col :span="5" >
                  <el-tag  closable @close="removeRightById(scope.row,item.id)">{{item.authName}}</el-tag>
                  <i class="el-icon-caret-right"></i>
                </el-col>
                <!--渲染二级和三级权限-->
                <el-col :span="19">
                  <!--通过for循环 嵌套渲染二级权限-->
                  <el-row :class="[i2 === 0 ? '':'bdtop']" v-for="(item2,i2) in item.children" :key="item2.id"
                          type="flex" align="middle">
                    <el-col :span="6">
                      <el-tag type="success"  closable @close="removeRightById(scope.row,item2.id)">
                        {{item2.authName}}
                      </el-tag>
                      <i class="el-icon-caret-right"></i>
                    </el-col>
                    <!--三级权限-->
                    <el-col :span="18">
                      <el-tag v-for="item3 in item2.children" :key="item3.id" type="warning" closable @close="removeRightById(scope.row,item3.id)">
                        {{item3.authName}}
                      </el-tag>
                    </el-col>
                  </el-row>
                </el-col>
              </el-row>
            </template>
          </el-table-column>
          <!--索引列-->
          <el-table-column type="index" label="ID" ></el-table-column>
          <el-table-column prop="roleName" label="角色名称" ></el-table-column>
          <el-table-column prop="roleDesc" label="角色描述" ></el-table-column>
          <el-table-column  label="操作列表">
            <template slot-scope="scope">
              <el-button size="mini" type="primary" icon="el-icon-edit">编辑</el-button>
              <el-button size="mini" type="danger" icon="el-icon-delete">删除</el-button>
              <el-button size="mini" type="warning" icon="el-icon-setting" @click="showSetRightDialog(scope.row)">分配权限</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!--分配权限-->
        <el-dialog
          title="分配权限"
          :visible.sync="setRightDialogVisible"
          width="50%">
            <span>
              <!-- 树形控件 -->
              <el-tree :data="rightList" :props="treeProps" show-checkbox
              node-key="id" default-expand-all :default-checked-keys="defKeys" ref="treeRef"></el-tree>
            </span>
              <span slot="footer" class="dialog-footer">
              <el-button @click="setRightDialogVisible = false">取 消</el-button>
              <el-button type="primary" @click="allotRights">确 定</el-button>
            </span>
        </el-dialog>
      </el-card>
    </div>
</template>

<script>
export default {
  name: 'roles',
  data () {
    return {
      // 当前即将分配权限的角色id
      roleId: '',
      // 所有角色列表数据
      rolesList: [],
      // 编辑权限列表对话框
      setRightDialogVisible: false,
      // 所有权限的数据
      rightList: [],
      // 树形控件的属性绑定对象
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      // 默认选择的节点的ID值
      defKeys: []
    }
  },
  methods: {
    async getRolesList () {
      // 获取所有角色的列表
      // eslint-disable-next-line no-unused-vars
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error('获取角色列表失败')
      this.rolesList = res.data
      this.$message.success('获取角色列表成功')
    },
    // 移除三级权限
    removeRightById (role, id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        // eslint-disable-next-line no-unused-vars
        const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${id}`)
        if (res.meta.status !== 200) return this.$message.error('删除失败')
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
        role.children = res.data
      }).catch(() => {
        console.log(role)
        console.log(role.children)
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 展示分配权限的对话框
    async showSetRightDialog (role) {
      // eslint-disable-next-line no-unused-vars
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) return this.$message.error('获取权限数据失败')
      this.rightList = res.data
      console.log(role)
      this.defKeys = []
      this.roleId = role.id
      this.getLeafKey(role, this.defKeys)
      this.setRightDialogVisible = true
    },
    // 通过递归获取角色下三级权限的id，并保存到defKeys中
    getLeafKey (node, arr) {
      // 当前节点无children属性则为三级节点
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.getLeafKey(item, arr)
      })
    },
    // 点击确定为角色分配权限
    async allotRights () {
      // eslint-disable-next-line no-unused-vars
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      // eslint-disable-next-line no-unused-vars
      const idStr = keys.join(',')
      // eslint-disable-next-line no-unused-vars
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: idStr })
      if (res.meta.status !== 200) return this.$message.error('分配权限失败')
      this.$message.success('分配权限成功')
      this.getRolesList()
      this.setRightDialogVisible = false
    }
  },
  created () {
    this.getRolesList()
  }
}
</script>

<style scoped>
  .el-tag {
    margin: 7px;
  }
  .bdtop {
    border-top: 1px solid #eee;
  }
  .bdbottom {
    border-bottom: 1px solid #eee;
  }
</style>
